package com.speedcar.base.util;

import com.speedcar.base.exception.ErrorCode;
import com.speedcar.base.exception.SpeedCarCheckException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
import java.util.stream.Collectors;

public class ValidationUtils {

    private static final Validator validator =
            Validation.buildDefaultValidatorFactory().getValidator();

    public static <T> void validate(T object) {
        Set<ConstraintViolation<T>> violations = validator.validate(object);
        if (!violations.isEmpty()) {
            String errorMsg = violations.stream()
                    .map(v -> v.getPropertyPath() + ": " + v.getMessage())
                    .collect(Collectors.joining("; "));
            throw new SpeedCarCheckException(ErrorCode.PARAM_ERROR, errorMsg);
        }
    }

    public static <T> void validate(T object, Class<?>... groups) {
        Set<ConstraintViolation<T>> violations = validator.validate(object, groups);
        if (!violations.isEmpty()) {
            String errorMsg = violations.stream()
                    .map(ConstraintViolation::getMessage)
                    .collect(Collectors.joining("; "));
            throw new SpeedCarCheckException(ErrorCode.PARAM_ERROR, errorMsg);
        }
    }
}
